package org.chnxi.study.nio.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取客户端发送过来的数据
     * 1. ChannelHandlerContext ctx：上下文对象，含有：管道pipeline、通道cahnnel、地址
     * 2. Object msg：就是客户端发送的数据，默认是Object
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //用户自定义异步处理任务，将任务加入至taskQueue中
        ctx.channel().eventLoop().execute(()->{
            try{
                TimeUnit.SECONDS.sleep(10);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~2[taskQueue]" , CharsetUtil.UTF_8));
                System.out.println("channelRead 线程名称："+Thread.currentThread().getName());
            }catch (Exception e){

            }
        });

        //用户自定义延时任务，将任务加入至scheduleTaskQueue
        ctx.channel().eventLoop().schedule(()->{
            try{
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~3[schedule task]" , CharsetUtil.UTF_8));
                System.out.println("channelRead 线程名称："+Thread.currentThread().getName());
            }catch (Exception e){

            }
        } , 5 , TimeUnit.SECONDS);

        ByteBuf buf = (ByteBuf)msg;
        System.out.println("客户端发送的消息是："+buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址是："+ ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //writeAndFlush 是 write + flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端~" , CharsetUtil.UTF_8));
    }

    //处理异常，一般是关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
